package com.hibiscusking.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        String requestURI = RequestContext.getCurrentContext().getRequest().getRequestURI();
        if (requestURI.endsWith("login")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        if (StringUtils.isBlank(token)){
            try {
                HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                Map<String,Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","未登录");
                map.put("resultObject","noLogin");
                String s = JSONObject.toJSONString(map);
                writer.write(s);
                RequestContext.getCurrentContext().setSendZuulResponse(false);
//                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
}
